package com.xixisleep.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xixisleep.api.common.ErrorCode;
import com.xixisleep.api.exception.BusinessException;
import com.xixisleep.api.mapper.UserInterfaceInfoMapper;

import com.xixisleep.api.service.UserInterfaceInfoService;
import com.xixisleep.apicommon.model.entity.UserInterfaceInfo;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author 傻傻小叶
* @description 针对表【user_interface_info】的数据库操作Service实现
* @createDate 2024-01-02 19:24:42
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {


    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            //判断接口信息对象是否为空，是则抛出参数错误异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获取接口信息对象的字段信息
        Long id = userInterfaceInfo.getId();
        Long userId = userInterfaceInfo.getUserId();
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
        Integer totalNum = userInterfaceInfo.getTotalNum();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        Integer status = userInterfaceInfo.getStatus();
        Date createTime = userInterfaceInfo.getCreateTime();
        Date undateTime = userInterfaceInfo.getUndateTime();
        Integer isDelete = userInterfaceInfo.getIsDelete();
        // 如果是添加操作
        if (add) {
            if (id <= 0 || userId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或用户不存在");
            }
        }
        if (leftNum < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"剩余次数不能小于0");
        }
    }

    /**
     * 调用接口统计
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    //todo 添加分布式锁，看伙伴匹配系统
    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        //校验
        if(interfaceInfoId <= 0 || userId <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //使用 updateWrapper 对象来构建更新条件
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId",interfaceInfoId);
        updateWrapper.eq("userId",userId);
        //setSql 方法用户设置要更新的sql预计，这里通过sql表达式实现了两个字段的更新操作
        updateWrapper.setSql("leftNum = leftNum - 1,totalNum = totalNum + 1");
        return this.update(updateWrapper);
    }
}




